package www.configure.all.modules.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import okhttp3.Request;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import www.configure.all.modules.websocket.StatusChangeWebsocketHandler;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class GetMaxLink {

    @Autowired
    private StatusChangeWebsocketHandler statusChangeWebsocketHandler;

    @Value("${getLinkNum.url}")
    private String maxLinkUrl;

    @Value("${local.host}")
    private String localHost;

    //单端口
    public void startUe() throws IOException {

        statusChangeWebsocketHandler.updateServerLink(1, localHost);

        startLogMonitor();

        statusChangeWebsocketHandler.startTurn();

    }

    //多端口
//    public void startUe() throws IOException {
//
//        OkHttpClient httpClient = new OkHttpClient();
//
//        String url = maxLinkUrl + localHost;
//
//        Request request = new Request.Builder()
//                .url(url)
//                .get()
//                .build();
//
//        try (Response response = httpClient.newCall(request).execute()) {
//            if (response.isSuccessful()) {
//                String body = response.body() != null ? response.body().string() : "无返回内容";
//                JSONObject jsonObject = JSON.parseObject(body);
//                if (jsonObject.getString("data") != null) {
//                    Integer maxLink = Integer.valueOf(jsonObject.getString("data"));
//                    System.out.println("maxLink: " + maxLink);
//                    System.out.println("localHost: " + localHost);
//                    statusChangeWebsocketHandler.updateServerLink(maxLink, localHost);
//                }
//            } else {
//                System.out.println("后端连接失败");
//            }
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//        // ***能启动多少个就启动多少个，使用需要注释上面的逻辑
////        statusChangeWebsocketHandler.startServer();
//
//        startLogMonitor();
//
//        statusChangeWebsocketHandler.startTurn();
//
//    }


    public void startLogMonitor() {
        File logFile = new File("./monitoring.log");
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.submit(() -> {
            try (BufferedReader reader = new BufferedReader(new FileReader(logFile))) {
                String line;
                while ((line = reader.readLine()) != null) { }
                while (true) {
                    line = reader.readLine();
                    if (line != null) {
                        if (line.contains("[UE OUT] Engine crash handling finished")) {
                            handleCrash();
                        }
                    } else {
                        Thread.sleep(100);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    private void handleCrash() throws IOException, InterruptedException {
        System.out.println("检测到 UE 崩溃日志，执行对应逻辑...");
        statusChangeWebsocketHandler.restartUe();
    }

}
